﻿using FileStorageCenter.Services.Models;
using FileStorageCenter.Services.Services;
using HelenServer.Modules.FileStorage.Abstractions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace FileStorageCenter.Services;

internal sealed class UploadHostedService : BackgroundService
{
    internal event EventHandler<UnobservedTaskExceptionEventArgs>? UnobservedTaskException;

    private readonly IUploadQueueProvider<UploadModel> _provider;

    private readonly ILogger<UploadHostedService> _logger;

    public UploadHostedService(IUploadQueueProvider<UploadModel> provider, ILogger<UploadHostedService> logger)
    {
        _provider = provider;
        _logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("Upload Queue hosted service is running.");

        stoppingToken.Register(() =>
           _logger.LogDebug($"Upload Queue hosted service is stopping."));

        while (!stoppingToken.IsCancellationRequested)
        {
            await BackgroundProcessing(stoppingToken);
        }

        _logger.LogCritical($"Upload Queue hosted service is stopped.");
    }

    private async Task BackgroundProcessing(CancellationToken stoppingToken)
    {
        try
        {
            await Task.Delay(100, stoppingToken);

            if (!_provider.IsEmpty)
            {
                var models = new List<UploadModel>();

                while (_provider.TryDequeue(out var model))
                {
                    models.Add(model);
                }

                using var scope = App.Services.CreateScope();

                var service = scope.ServiceProvider.GetRequiredService<IFileStorageService>();

                await service.UploadFileRangeAsync(models, stoppingToken);
            }
        }
        catch (Exception)
        {

        }
    }
}